<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CInvoiceApplyForm">
          <a-row>


            <a-divider >发票信息</a-divider >
            <a-col :span="8">
              <a-form-item label="发票类型" v-bind="validateInfos.invoiceType" id="CInvoiceApplyForm-invoiceType" name="invoiceType">
                <a-input v-model:value="formData.invoiceType" placeholder="请输入发票类型"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
					   <a-col :span="8">
					  	<a-form-item label="发票号码" v-bind="validateInfos.invoiceNumber" id="CInvoiceApplyForm-invoiceNumber" name="invoiceNumber">
					  		<a-input v-model:value="formData.invoiceNumber" placeholder="请输入发票号码"  allow-clear ></a-input>
					  	</a-form-item>
					  </a-col>

             <a-col :span="8">
              <a-form-item label="开票日期" v-bind="validateInfos.invoiceDate" id="CInvoiceApplyForm-invoiceDate" name="invoiceDate">
                <a-date-picker placeholder="请选择开票日期"  v-model:value="formData.invoiceDate" value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
              </a-form-item>
            </a-col>

            <a-divider >销售采购方信息</a-divider >
					   <a-col :span="12">
					  	<a-form-item label="购买方名称" v-bind="validateInfos.buyName" id="CInvoiceApplyForm-buyName" name="buyName">
					  		<a-input v-model:value="formData.buyName" placeholder="请输入购买方名称"  allow-clear ></a-input>
					  	</a-form-item>
					  </a-col>
					   <a-col :span="12">
					  	<a-form-item label="购买方纳税人识别号" v-bind="validateInfos.buyTaxId" id="CInvoiceApplyForm-buyTaxId" name="buyTaxId">
					  		<a-input v-model:value="formData.buyTaxId" placeholder="请输入购买方统一社会信用代码/纳税人识别号"  allow-clear ></a-input>
					  	</a-form-item>
					  </a-col>
					   <a-col :span="12">
					  	<a-form-item label="销售方名称" v-bind="validateInfos.sellerName" id="CInvoiceApplyForm-sellerName" name="sellerName">
					  		<a-input v-model:value="formData.sellerName" placeholder="请输入销售方名称"  allow-clear ></a-input>
					  	</a-form-item>
					  </a-col>
					   <a-col :span="12">
					  	<a-form-item label="销售方纳税人识别号" v-bind="validateInfos.sellerTaxId" id="CInvoiceApplyForm-sellerTaxId" name="sellerTaxId">
					  		<a-input v-model:value="formData.sellerTaxId" placeholder="请输入销售方统一社会信用代码/纳税人识别号"  allow-clear ></a-input>
					  	</a-form-item>
					  </a-col>


            <a-divider >开票信息</a-divider >
            <a-col :span="8">
              <a-form-item label="合计税额" v-bind="validateInfos.totalTaxAmount" id="CInvoiceApplyForm-totalTaxAmount" name="totalTaxAmount">
                <a-input v-model:value="formData.totalTaxAmount" placeholder="请输入合计税额"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="合计金额" v-bind="validateInfos.totalAmount" id="CInvoiceApplyForm-totalAmount" name="totalAmount">
                <a-input v-model:value="formData.totalAmount" placeholder="请输入合计金额"  allow-clear ></a-input>
              </a-form-item>
            </a-col>

            <a-col :span="8">
              <a-form-item label="价税合计" v-bind="validateInfos.totalAmountWithTax" id="CInvoiceApplyForm-totalAmountWithTax" name="totalAmountWithTax">
                <a-input-number v-model:value="formData.totalAmountWithTax" placeholder="请输入价税合计" style="width: 100%" />
              </a-form-item>
            </a-col>

            <a-col :span="12" v-show="false">
              <a-form-item label="价税合计（大写）" v-bind="validateInfos.totalAmountWithTaxUpper" id="CInvoiceApplyForm-totalAmountWithTaxUpper" name="totalAmountWithTaxUpper">
                <a-input v-model:value="formData.totalAmountWithTaxUpper" placeholder="请输入价税合计（大写）"  allow-clear ></a-input>
              </a-form-item>
            </a-col>

            <table  class="simple-table">
              <thead>
                <tr>
                  <th style="width: 12%">项目名称</th>
                  <th style="width: 12%">建筑服务发生地</th>
                  <th style="width: 12%">建筑项目名称</th>
                  <th style="width: 12%">金额</th>
                  <th style="width: 12%">税率(%)</th>
                  <th style="width: 12%">税额</th>

                </tr>
              </thead>
              <tbody>
              <tr>
                <td><a-input v-model:value="formData.projectName" placeholder="请输入项目名称"  allow-clear ></a-input></td>
                <td><a-input v-model:value="formData.buildingProjectsAdd" placeholder="请输入建筑服务发生地"  allow-clear ></a-input></td>
                <td><a-input v-model:value="formData.buildingProjects" placeholder="请输入建筑项目名称"  allow-clear ></a-input></td>
                <td><a-input-number v-model:value="formData.amount" placeholder="请输入金额" style="width: 100%" /></td>
                <td><a-input-number v-model:value="formData.taxRate" placeholder="请输入税率/征收率" style="width: 100%" /></td>
                <td><a-input-number v-model:value="formData.taxAmount" placeholder="请输入税额" style="width: 100%" /></td>
              </tr>
              </tbody>
            </table>



						 <a-col :span="24" v-show="false">
							<a-form-item label="开票人" v-bind="validateInfos.invoicer" id="CInvoiceApplyForm-invoicer" name="invoicer">
								<a-input v-model:value="formData.invoicer" placeholder="请输入开票人"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						 <a-col :span="24" v-show="false">
							<a-form-item label="备注" v-bind="validateInfos.remarks" id="CInvoiceApplyForm-remarks" name="remarks">
								<a-textarea v-model:value="formData.remarks" :rows="4" placeholder="请输入备注" />
							</a-form-item>
						</a-col>
						
						
					
						
						


            <a-divider >补充信息</a-divider >
            <a-col :span="12">
              <a-form-item label="标题" v-bind="validateInfos.title" id="CInvoiceApplyForm-title" name="title">
                <a-input v-model:value="formData.title" placeholder="请输入标题"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
             <a-col :span="12">
              <a-form-item label="主项目" v-bind="validateInfos.projectId" id="CSubProjectForm-projectId" name="projectId">
                <j-dict-select-tag showSearch="true"    v-model:value="formData.projectId"
                                   dictCode="c_project_application,project_name,id" placeholder="请输入主项目"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="总包信息" v-bind="validateInfos.companyInfoId" id="CSubProjectForm-companyInfoId" name="companyInfoId">
                <j-dict-select-tag showSearch="true"    v-model:value="formData.companyInfoId"
                                   dictCode="c_company_info,company_name,id" placeholder="请输入总包信息"  allow-clear />
              </a-form-item>
            </a-col>
             <a-col :span="12">
              <a-form-item label="开票阶段" v-bind="validateInfos.stage" id="CInvoiceApplyForm-stage" name="stage">
                <a-input v-model:value="formData.stage" placeholder="请输入开票阶段"  allow-clear ></a-input>
                <!--					  		 <j-dict-select-tag showSearch="true"   v-model:value="formData.stage" placeholder="请输入开票阶段" dictCode="Invoicing_progress"  allow-clear />-->
              </a-form-item>
            </a-col>
             <a-col :span="12">
              <a-form-item label="发票" v-bind="validateInfos.billFile" id="CInvoiceApplyForm-billFile" name="billFile">
                <j-upload v-model:value="formData.billFile" dragger="true"
                          :showUploadList="{ showRemoveIcon: true, showDownloadIcon: true }"  ></j-upload>
              </a-form-item>
            </a-col>
             <a-col :span="12">
              <a-form-item label="附件" v-bind="validateInfos.attachmentUrl" id="CInvoiceApplyForm-attachmentUrl" name="attachmentUrl">
                <j-upload v-model:value="formData.attachmentUrl" dragger="true"
                          :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"  ></j-upload>
              </a-form-item>
            </a-col>




						
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
    import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CInvoiceApply.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
	projectId:'',
    projectName: '',   
    taxAmount: undefined,
    invoiceDate: '',   
    invoicer: '',   
    invoiceType: '',   
    totalAmountWithTax: undefined,
    taxRate: undefined,
    totalAmountWithTaxUpper: '',   
    remarks: '',   
    invoiceNumber: '',   
    amount: undefined,
    sellerName: '',   
    sellerTaxId: '',   
    buyName: '',   
    buyTaxId: '',   
    billFile: '',   
    attachmentUrl: '', 
	totalTaxAmount: '', 
	totalAmount: '', 
    status: '',   
    stage: '', 
	buildingProjects:'',
	buildingProjectsAdd:'',
    companyInfoId:'',
    title:'',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    taxAmount: [{ required: true, message: '请输入税额!'},],
    invoiceDate: [{ required: true, message: '请输入开票日期!'},],
    invoicer: [{ required: true, message: '请输入开票人!'},],
    invoiceType: [{ required: true, message: '请输入发票类型!'},],
    totalAmountWithTax: [{ required: true, message: '请输入价税合计（小写）!'},],
    taxRate: [{ required: true, message: '请输入税率/征收率!'},],
    totalAmountWithTaxUpper: [{ required: true, message: '请输入价税合计（大写）!'},],
	//projectId: [{ required: true, message: '请输入主项目!'},],
    invoiceNumber: [{ required: true, message: '请输入发票号码!'},],
    amount: [{ required: true, message: '请输入金额!'},],
    sellerName: [{ required: true, message: '请输入销售方名称!'},],
    sellerTaxId: [{ required: true, message: '请输入销售方统一社会信用代码/纳税人识别号!'},],
    buyName: [{ required: true, message: '请输入购买方名称!'},],
    buyTaxId: [{ required: true, message: '请输入购买方统一社会信用代码/纳税人识别号!'},],
    auditFile: [{ required: true, message: '请输入财务审核相关文件!'},],
	totalTaxAmount: [{ required: true, message: '请输入合计税额!'},],
	totalAmount: [{ required: true, message: '请输入合计金额!'},],
    stage: [{ required: true, message: '请输入开票阶段!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }

  /* 表格整体边框 */
  .simple-table {
    width: 100%;
    border-collapse: collapse; /* 合并边框 */
    border: 1px solid #000;
  }

  /* 表头蓝底白字 */
  .simple-table th {
    background: #eaf0fa;
    color: #070707;
    padding: 6px 4px;
    border: 1px solid #000;
    text-align: center;
  }

  /* 单元格边框 */
  .simple-table td {
    border: 1px solid #000;
    padding: 0;
  }

  /* 输入框铺满单元格 */
  .simple-table input {
    width: 100%;
    box-sizing: border-box;
    border: none;
    outline: none;
    padding: 6px 4px;
    background: transparent;
  }

</style>
